package com.zheng.study.base.bean.search;

import com.zheng.study.base.bean.search.order.Order;
import com.zheng.study.base.bean.search.page.Page;
import com.zheng.study.base.bean.search.page.PagePaging;
import com.zheng.study.base.bean.search.page.PageUnique;
import com.zheng.study.base.bean.search.rule.Rule;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询
 * ============================================================================
 * author : fallenpanda
 * createDate:  2018/6/12 。
 * ============================================================================
 */
public class Search {

	private final Page page;
	private final List<Rule> rules;
	private final List<Order> orders;

	public Search(Page page, List<Rule> rules, List<Order> orders) {
		this.page = page;
		this.rules = rules;
		this.orders = orders;
	}

	public Page getPage() {
		return page;
	}

	public List<Rule> getRules() {
		return rules;
	}

	public List<Order> getOrders() {
		return orders;
	}

	public static Search simpleSearchList(){
		return newBuilder().setPage(PagePaging.simplePage()).addOrder(Order.simpleOrder()).build();
	}

	public static Search simpleSearchUniqueResult(){
		return newBuilder().setPage(PageUnique.uniqueResult()).addOrder(Order.simpleOrder()).build();
	}

	public static Builder newBuilder(){
		return new Builder();
	}

	public static class Builder{

		private Page page;
		private List<Rule> rules;
		private List<Order> orders;

		public Builder setPage(Page page) {
			this.page = page;
			return this;
		}

		public Builder setRules(List<Rule> rules) {
			this.rules = rules;
			return this;
		}

		public Builder addRule(Rule rule){
			if(null == this.rules){
				this.rules = new ArrayList<Rule>();
			}
			this.rules.add(rule);
			return this;
		}

		public Builder addRules(List<Rule> rules){
			if(null == this.rules){
				this.rules = new ArrayList<Rule>();
			}
			this.rules.addAll(rules);
			return this;
		}

		public Builder setOrders(List<Order> orders) {
			this.orders = orders;
			return this;
		}

		public Builder addOrder(Order order){
			if(null == this.orders){
				this.orders = new ArrayList<Order>();
			}
			this.orders.add(order);
			return this;
		}

		public Builder addOrders(List<Order> orders){
			if(null == this.orders){
				this.orders = new ArrayList<Order>();
			}
			this.orders.addAll(orders);
			return this;
		}

		public Builder addOrders(Order... orders){
			if(null == this.orders){
				this.orders = new ArrayList<Order>();
			}
			if(orders != null && orders.length > 0){
				for(Order order:orders){
					this.orders.add(order);
				}
			}
			return this;
		}

		public Search build(){
			Assert.notNull(page, "pager 不能为空");
			return new Search(page, rules, orders);
		}

	}

}
